from django.shortcuts import render
from django.core.paginator import Paginator
#引入FoodCook类
from foodCook.models import FoodCook
from django.db.models import Max
#引入JsonResponse模块
from django.http import JsonResponse
#导入json模块
import json
#导入uuid模块
import uuid
#导入哈希模块
import hashlib
import os
from django.conf import settings

#获取食谱信息
def get_foodcooks(request):
    """获取全部食谱信息"""
    try:
        obj_foodcook=FoodCook.objects.all().values()
        #使用ORM获取所有信息
        #把结果转为list
        foodcooks=list(obj_foodcook)
        return JsonResponse({'code':1,'data':foodcooks})
    except Exception as e:
        return JsonResponse({'code':0,'msg':'获取食谱信息错误。'+str(e)})


def my_view(request):
    # 假设每页显示10个对象
    per_page = 10

    # 获取查询集（例如：MyModel.objects.all()）
    my_objects = ...

    # 创建Paginator对象
    paginator = Paginator(my_objects, per_page)

    # 从GET请求中获取页码
    page_number = request.GET.get('page')

    # 获取具体页码的Page对象
    page_obj = paginator.get_page(page_number).pages[page_number]

    # 将Page对象传递到模板中
    return render(request, 'my_template.html', {'page_obj': page_obj})

# 分页获取食谱数据
def getPage_foodcooks(request):
    # 假设每页显示10个对象
    """获取全部食谱信息"""
    try:
        per_page = 4
        # 获取查询集（例如：MyModel.objects.all()）
        my_objects = FoodCook.objects.all().order_by('cookNo').values()
        # 创建Paginator对象
        paginator = Paginator(my_objects, per_page)
        numPage=paginator.num_pages
        print(numPage)
        # 从GET请求中获取页码
        page_number = request.GET.get('page')
        try:
            page_number = int(page_number)
            # if page_number<=Paginator.num_pages and page_number>=1:
            #     # 获取具体页码的Page对象
            page_obj = paginator.get_page(page_number)
            # else:
            #     page_obj = paginator.get_page(1)
        except:
            # 获取具体页码的Page对象
            page_obj = paginator.get_page(1)

        # obj_foodcook=FoodCook.objects.all().values()
        #使用ORM获取所有信息
        #把结果转为list
        foodcooks=list(page_obj.object_list)
        return JsonResponse({'code':1,'data':foodcooks,'pageCout':numPage})
    except Exception as e:
        return JsonResponse({'code':0,'msg':'获取食谱信息错误。'+str(e)})

#查询食谱信息
def query_cooks(request):
    #接受查询条件，并将接收数据解析为json
    # print(request.body)
    data=json.loads(request.body.decode('utf-8'))
    print(data)
    #查询学生信息
    try:
        # print(data.keys())
        obj_res=FoodCook.objects
        for key in data.keys():
            if key=='cookName':
                obj_res=obj_res.filter(cookName__icontains=data[key])
            if key=='cookDes':
                obj_res=obj_res.filter(functionDes__icontains=data[key])
            if key=='foods':
                obj_res=obj_res.filter(foods__icontains=data[key])
        obj_res=obj_res.order_by('cookNo').values()
        # 创建Paginator对象
        paginator = Paginator(obj_res, 4)
        numPage = paginator.num_pages
        page_number=data['page']
        page_obj = paginator.get_page(page_number)
        obj_cook=list(page_obj.object_list)
        return JsonResponse({'code':1,'data':obj_cook,'pageCout':numPage})
    except Exception as e:
        return JsonResponse({'code':0,'msg':e})
    pass
# 添加食谱到数据库
def add_foodcooks(request):
    data=json.loads(request.body.decode('utf-8'))

    max_cookno = FoodCook.objects.aggregate(Max('cookNo'))['cookNo__max']
    if max_cookno!=None:
        data['cookNo']=max_cookno+1
    else:
        data['cookNo']=100001
    print(data)
#     添加到数据库
    try:
        obj_foodcook=FoodCook(cookNo=data['cookNo'],cookName=data['cookName'],functionDes=data['functionDes'],foods=data['foods'],
                            cookAddress=data['cookAddress'],image=data['image'])
        obj_foodcook.save()
        obj_foodcooks = FoodCook.objects.all().values()
        # 使用ORM获取所有学生信息
        # 把结果转为list
        foodcooks = list(obj_foodcooks)
        return JsonResponse({'code': 1})
    except Exception as e:
        return  JsonResponse({'code':0,'message':f"添加到数据库异常，请联系管理员！\n{e}"})

# 编辑学生信息
def edit_cook(request):
    data=json.loads(request.body.decode('utf-8'))
    print(data)
    try:
        # 查找到要修改的学生信息
        obj_cook = FoodCook.objects.get(cookNo=data['cookNo'])
        # 依次修改字段
        obj_cook.functionDes=data['functionDes']
        obj_cook.foods=data['foods']
        obj_cook.cookAddress=data['cookAddress']
        obj_cook.image=data['image']

        obj_cook.save()
        obj_students = FoodCook.objects.all().values()
        # 使用ORM获取所有学生信息
        # 把结果转为list
        return JsonResponse({'code': 1})
    except Exception as e:
        return JsonResponse({'code': 0, 'message': "修改数据库异常，请联系管理员！"})

#检查学号
def is_exsits_cookName(request):
    #判断接收学号
    data=json.loads(request.body.decode('utf-8'))
    obj_student = FoodCook.objects.filter(cookName=data['cookName'])
    try:
        if obj_student.count()==0:
            return JsonResponse({'code':1,'exsits':False})
        else:
            return JsonResponse({'code': 1, 'exsits': True})
    except Exception as e:
        return JsonResponse({'code': 1, 'message': '校验食谱失败！请联系管理员。'})



def upload_file(request):
#     接受上传文件
    rev_file=request.FILES.get('file_name')
    if not rev_file:
        return  JsonResponse({'code':0,'msg':'图片不存在'})
#     获得一个唯一的名字：uuid+哈希
    new_name=get_random_str()
    #准备写入的URL
    file_path=os.path.join(settings.MEDIA_ROOT_COOK,new_name+os.path.splitext(rev_file.name)[1])
    print(file_path)
    #写入本地磁盘
    try:
        #xieru
        f=open(file_path,'wb')
        for i in rev_file.chunks():
            f.write(i)
        f.close()
        return JsonResponse({'code':1,'name':new_name+os.path.splitext(rev_file.name)[1]})
    except Exception as e:
        return JsonResponse({'code':0,'msg':str(e)})


def get_random_str():
    #获取UUID随机数
    uuid_val=uuid.uuid4()
    #获取uuid的随机字符串
    uuid_str=str(uuid_val).encode('utf-8')
    #获取MD5实例
    md5=hashlib.md5()
    #拿去md5摘要
    md5.update(uuid_str)
    #返回固定长度的字符串
    return md5.hexdigest()



